package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import javax.swing.plaf.ToolBarUI;
import java.util.Date;


@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {


    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    WemediaFeign wemediaFeign;


    /**
     * 查询待审核的用户信息
     * @param
     * @return
     */
    @Override
    public PageResponseResult loadListByStatus(AuthDTO dto) {
        //判断传递的参数
        //如果什么都没传 表示默认的分页  查询状态所有
        dto.checkParam();

        //分页
        Page<ApUserRealname> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        //创建条件查询符合状态的
        if (dto.getStatus() != null){
            //表示有状态  按照状态为条件来查询
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        //添加添加  ==>  需要判断的条件
//        wrapper.eq(dto.getStatus()!=null,ApUserRealname::getStatus,dto.getStatus());
        IPage<ApUserRealname> userPage = this.page(page, wrapper);


        return new PageResponseResult(dto.getPage(),dto.getSize(),userPage.getTotal(),userPage.getRecords());
    }





    /**
     * 处理审核
     * @param dto
     * @param
     * @return
     */
    @GlobalTransactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //判断数据  判断前段传递过来的  待审核的用户id  是否存在
        if (dto.getId() == null){
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"缺少待审核用户id");
        }
        //根据id获取对象
        ApUserRealname apUserRealname = getById(dto.getId());
        //判断对象是否存在
        if (apUserRealname == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"该用户不存在");
        }
        //判断用户的状态
        if (apUserRealname.getStatus() != 1){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"该用户不需要审核");
        }
        //根据审核对象中的userId查询对应的对象
        ApUser apUser = apUserMapper.selectById(apUserRealname.getUserId());
        //判断用户是否存在
        if (apUser == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证关联的app用户不存在");
        }

        // 更改用户状态  修改时间  设置驳回信息
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if (dto.getMsg()!=null){
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);


        //表示状态码为 9 调用方法
        if (status.equals(AdminConstants.PASS_AUTH)){
            //表示通过申请 创建 自媒体用户 和 作者信息
            WmUser wmUser = createWmUser(dto, apUser);
            //添加作者
            createApAuthor(wmUser);
        }
//        System.out.println(1/0);

        //返回修改成功结果
        return ResponseResult.okResult();
    }


    /**
     * 创建作者对象
     * @param wmUser
     */
    private void createApAuthor(WmUser wmUser) {
        //根据userid查询作者信息
        ResponseResult<ApAuthor> authorResponseResult = articleFeign.findByUserId(wmUser.getApUserId());
        //状态码不为0  表示出错
        if (authorResponseResult.getCode() != 0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,authorResponseResult.getErrorMessage());
        }
        ApAuthor apAuthor = authorResponseResult.getData();
        if (apAuthor != null){
            //表示作者已存在
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"该用户已经注册作者");
        }

        ApAuthor newApAuthor = new ApAuthor();

        newApAuthor.setName(wmUser.getName());
        newApAuthor.setType(AdminConstants.AUTHOR_TYPE);
        newApAuthor.setUserId(wmUser.getApUserId());
        newApAuthor.setCreatedTime(new Date());
        newApAuthor.setWmUserId(wmUser.getId());

        //调用方法存储作者
        ResponseResult<ApAuthor> apAuthorResponseResult = articleFeign.saveAuthor(newApAuthor);
        if (apAuthorResponseResult.getCode() != 0){
            //调用出错
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,apAuthorResponseResult.getErrorMessage());
        }
    }


    /**
     * 添加自媒体用户
     * @param dto
     * @param apUser
     * @return
     */
    public WmUser createWmUser(AuthDTO dto, ApUser apUser){

        //获取自媒体用户信息
        ResponseResult<WmUser> wmUser = wemediaFeign.findByName(apUser.getName());
        //判断状态
        if (wmUser.getCode().intValue() != 0 ){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,wmUser.getErrorMessage());
        }
        if (wmUser.getData() != null){
            //表示未审核账号已注册了自媒体
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"该账号已经注册自媒体用户");
        }

        //填充参数
        WmUser newWmUser = new WmUser();
        newWmUser.setApUserId(apUser.getId());
        newWmUser.setName(apUser.getName());
        newWmUser.setPassword(apUser.getPassword());
        newWmUser.setSalt(apUser.getSalt());
        newWmUser.setPhone(apUser.getPhone());
        newWmUser.setStatus(AdminConstants.PASS_AUTH.intValue());
        newWmUser.setType(0);
        newWmUser.setCreatedTime(new Date());

        //调用方法添加用户
        ResponseResult<WmUser> newWmUserResult = wemediaFeign.addWmUser(newWmUser);
        if (newWmUserResult.getCode() != 0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,newWmUserResult.getErrorMessage());
        }
        return newWmUserResult.getData();
    }








}
